import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import urlparse
from dateutil import parser

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from django.utils import simplejson as json
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from models import *
from utilities import *

webapp.template.register_template_library('customfilters')
webapp.template.register_template_library('smart_if')


# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True


class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'application_name': 'Fieltro',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('admin', template_name))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings'
    self.response.out.write(template.render(path, values, debug=_DEBUG))

    
class Index(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('index.html', template_values)


class Blogs(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Blog.all()
    queryitems.order('-pubDate')
    blogs = queryitems.fetch(500)

    template_values = {
      'blogs': blogs,
    }
    self.generate('blogs.html', template_values)


class BlogAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Blog.get(itemkey)
      item.delete()
      self.redirect("/admin/blogs", False)
      return 1

    elif action=='edit':
      try:
        item = Blog.get(itemkey)
      except:
        queryitem = Blog.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      name = item.name
      url = item.url
      slug = item.slug
      email = item.email
      author = item.author
      firstPost = item.firstPost
      country = item.country
      description = item.description
      pubDate = item.pubDate
      twitter = item.twitter
      firstMonth = item.firstMonth
      firstYear = item.firstYear

      template_values = {
        'name': name,
        'author': author,
        'url': url,
        'slug': slug,
        'email': email,
        'firstPost': firstPost,
        'country': country,
        'description': description,
        'pubDate': pubDate,
        'twitter': twitter,
        'firstMonth': firstMonth,
        'firstYear': firstYear,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("blog.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Blog.get(itemkey)
      creating = False
    else:
      item = Blog()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Blog.all()
        queryitem.order('-blogId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].blogId
          
        blogId = lastId + 1
        item.blogId = blogId
      
      item.name = self.request.get("name")
      item.url = self.request.get("url")
      item.slug = self.request.get("slug")
      item.author = self.request.get("author")
      item.email = self.request.get("email")
      item.firstPost = parser.parse(self.request.get('firstPost'))
      item.country = self.request.get("country")
      item.description = self.request.get("description")
      item.twitter = self.request.get("twitter")
      item.firstMonth = self.request.get("firstMonth")
      item.firstYear = self.request.get("firstYear")
      item.put()
      
    self.redirect("/admin/blogs", True)


class Libros(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Libro.all()
    queryitems.order('-pubDate')
    libros = queryitems.fetch(500)

    template_values = {
      'libros': libros,
    }
    self.generate('libros.html', template_values)


class LibroAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Libro.get(itemkey)
      item.delete()
      self.redirect("/admin/libros", False)
      return 1

    elif action=='edit':
      try:
        item = Libro.get(itemkey)
      except:
        queryitem = Libro.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      name = item.name
      slug = item.slug
      author = item.author
      country = item.country
      description = item.description
      pubDate = item.pubDate
      language = item.language

      template_values = {
        'name': name,
        'author': author,
        'slug': slug,
        'country': country,
        'description': description,
        'pubDate': pubDate,
        'key': itemkey,
        'language': language,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("libro.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Libro.get(itemkey)
      creating = False
    else:
      item = Libro()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Libro.all()
        queryitem.order('-libroId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].libroId
          
        libroId = lastId + 1
        item.libroId = libroId
      
      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.author = self.request.get("author")
      item.country = self.request.get("country")
      item.description = self.request.get("description")
      item.language = self.request.get("language")
      item.put()
      
    self.redirect("/admin/libros", True)


class Videos(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Video.all()
    queryitems.order('-pubDate')
    videos = queryitems.fetch(500)

    template_values = {
      'videos': videos,
    }
    self.generate('videos.html', template_values)


class VideoAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Video.get(itemkey)
      item.delete()
      self.redirect("/admin/videos", False)
      return 1

    elif action=='edit':
      try:
        item = Video.get(itemkey)
      except:
        queryitem = Video.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      title = item.title
      slug = item.slug
      url = item.url
      description = item.description
      code = item.code
      pubDate = item.pubDate

      template_values = {
        'title': title,
        'slug': slug,
        'url': url,
        'description': description,
        'code': code,
        'pubDate': pubDate,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("video.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Video.get(itemkey)
      creating = False
    else:
      item = Video()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Video.all()
        queryitem.order('-videoId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].videoId
          
        videoId = lastId + 1
        item.videoId = videoId
      
      item.title = self.request.get("title")
      item.slug = self.request.get("slug")
      item.url = self.request.get("url")
      item.description = self.request.get("description")
      item.code = self.request.get("code")
      item.put()
      
    self.redirect("/admin/videos", True)

class Revistas(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Revista.all()
    queryitems.order('-pubDate')
    revistas = queryitems.fetch(500)

    template_values = {
      'revistas': revistas,
    }
    self.generate('revistas.html', template_values)


class RevistaAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Revista.get(itemkey)
      item.delete()
      self.redirect("/admin/revistas", False)
      return 1

    elif action=='edit':
      try:
        item = Revista.get(itemkey)
      except:
        queryitem = Revista.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      name = item.name
      slug = item.slug
      country = item.country
      description = item.description
      pubDate = item.pubDate
      language = item.language

      template_values = {
        'name': name,
        'slug': slug,
        'country': country,
        'description': description,
        'pubDate': pubDate,
        'key': itemkey,
        'language': language,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("revista.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Revista.get(itemkey)
      creating = False
    else:
      item = Revista()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Revista.all()
        queryitem.order('-revistaId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].revistaId
          
        revistaId = lastId + 1
        item.revistaId = revistaId
      
      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.country = self.request.get("country")
      item.description = self.request.get("description")
      item.language = self.request.get("language")
      item.put()
      
    self.redirect("/admin/revistas", True)


class PR_Projects(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = PR_Project.all()
    queryitems.order('name')
    projects = queryitems.fetch(500)
    
    queryitems = PR_Server.all()
    queryitems.order('name')
    servers = queryitems.fetch(500)

    template_values = {
      'projects': projects,
      'servers': servers,
    }
    self.generate('projects.html', template_values)


class PR_ProjectAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
      
    queryitems = PR_Server.all()
    queryitems.order('name')
    servers = queryitems.fetch(500)

    if action == 'delete':
      item = Project.get(itemkey)
      item.delete()
      self.redirect("/admin/projects", False)
      return 1

    elif action=='edit':
      try:
        item = PR_Project.get(itemkey)
      except:
        queryitem = Project.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]
      
      template_values = {
        'servers': servers,
        'project': item,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
        'servers': servers,
      }

    self.generate("project.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = PR_Project.get(itemkey)
      creating = False
    else:
      item = PR_Project()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = PR_Project.all()
        queryitem.order('-projectId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].projectId
          
        projectId = lastId + 1
        item.projectId = projectId
      
      item.url = self.request.get("url")
      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.server = self.request.get("server")
      item.lang = self.request.get("lang")
      item.status = self.request.get("status")
      item.favicon = self.request.get("favicon")
      item.put()
      
    self.redirect("/admin/projects", True)

class PR_Servers(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = PR_Server.all()
    queryitems.order('name')
    servers = queryitems.fetch(500)

    template_values = {
      'servers': servers,
    }
    self.generate('servers.html', template_values)


class PR_ServerAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = PR_Server.get(itemkey)
      item.delete()
      self.redirect("/admin/servers", False)
      return 1

    elif action=='edit':
      try:
        item = PR_Server.get(itemkey)
      except:
        queryitem = PR_Server.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      template_values = {
        'server': item,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("server.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = PR_Server.get(itemkey)
      creating = False
    else:
      item = PR_Server()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = PR_Server.all()
        queryitem.order('-serverId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].serverId
          
        serverId = lastId + 1
        item.serverId = serverId
      
      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.put()
      
    self.redirect("/admin/servers", True)

class PR_Links(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = PR_Link.all()
    queryitems.order('-pubDate')
    links = queryitems.fetch(500)

    template_values = {
      'links': links,
    }
    self.generate('links.html', template_values)


class PR_LinkAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
      
    queryitems = PR_Project.all()
    queryitems.order('name')
    projects = queryitems.fetch(500)

    if action == 'delete':
      item = PR_Link.get(itemkey)
      item.delete()
      self.redirect("/admin/links", False)
      return 1

    elif action=='edit':
      try:
        item = PR_Link.get(itemkey)
      except:
        queryitem = Link.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      template_values = {
        'projects': projects,
        'link': item,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
        'projects': projects,
      }

    self.generate("link.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = PR_Link.get(itemkey)
      creating = False
    else:
      item = PR_Link()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = PR_Link.all()
        queryitem.order('-linkId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].linkId
          
        linkId = lastId + 1
        item.linkId = linkId
      
      item.linker = self.request.get("linker")
      item.linked = self.request.get("linked")
      
      if self.request.get("category"):
        item.categoryId = int(self.request.get("category"))
      item.put()
      
    self.redirect("/admin/links", True)

class Galleries(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Gallery.all()
    queryitems.order('-pubDate')
    items = queryitems.fetch(500)

    querytags = GalleryTag.all()
    querytags.order('name')
    tags = querytags.fetch(100)

    template_values = {
      'galleries': items,
      'tags': tags
    }
    self.generate('galleries.html', template_values)

class GalleryAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    category = self.request.get("c")
    
    if action == 'delete':
      item = Gallery.get(itemkey)
      item.delete()
      self.redirect("/admin/galleries/", False)
      return 1

    elif action=='edit':
      try:
        item = Gallery.get(itemkey)
      except:
        queryitem = Gallery.all()
        queryitem.filter(' galleryId = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      title = item.title
      pubDate = item.pubDate
      key = str(item.key())
      galleryId = item.galleryId
      galleryTags = item.tags
      category = item.category
      
      querytags = GalleryTag.all()
      querytags.order('name')
      tags = querytags.fetch(100)
      
      queryphotos = File.all()
      queryphotos.filter(' galleryId = ', int(galleryId))
      photos = queryphotos.fetch(50)

      template_values = {
        'title': title,
        'pubDate': pubDate,
        'galleryId': galleryId,
        'galleryTags': galleryTags,
        'tags': tags,
        'category': category,
        'photos': photos,
      }
    elif action=='new':
      
      querytags = GalleryTag.all()
      querytags.order('name')
      tags = querytags.fetch(100)
      
      template_values = {
        'tags': tags,
        'category': category,
      }
    self.generate("gallery.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      queryitem = Gallery.all()
      queryitem.filter(' galleryId = ', int(itemkey))
      items = queryitem.fetch(1)
      item = items[0]
      creating = False
    else:
      item = Gallery()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest galleryId used, increase it by 1 and use it
        queryitem = Gallery.all()
        queryitem.order('-galleryId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].galleryId
          
        galleryId = lastId + 1
        item.galleryId = galleryId
      
      item.title = self.request.get("title")
      item.category = self.request.get("category")
      item.tags = self.request.POST.getall("tag")
      
      item.put()
      
    self.redirect("/admin/galleries/", True)

class PublishGallery(webapp.RequestHandler):
  def post(self, id):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)

    querygallery = Gallery.all()
    querygallery.filter(' galleryId = ', int(galleryId))
    galleries = querygallery.fetch(1)
    gallery = galleries[0]
    gallery.draft = False
    gallery.put()

    self.response.out.write("Happy end")

class UnpublishGallery(webapp.RequestHandler):
  def post(self, id):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)

    querygallery = Gallery.all()
    querygallery.filter(' galleryId = ', int(galleryId))
    galleries = querygallery.fetch(1)
    gallery = galleries[0]
    gallery.draft = True
    gallery.put()

    self.response.out.write("Happy end")

class GalleryTags(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    querytags = GalleryTag.all()
    querytags.order('name')
    tags = querytags.fetch(500)

    template_values = {
      'tags': tags,
    }
    self.generate('gallerytags.html', template_values)

class GalleryTagAction(BaseRequestHandler):
  def get(self, key, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      tag = GalleryTag.get(key)
      tag.delete()
      template_values = {}
      self.redirect("/admin/gallerytags/", True)
      return 1

    elif action=='edit':
      tag = GalleryTag.get(key)
      name = tag.name
      slug = tag.slug

      template_values = {
        'name': name,
        'slug': slug,
      }
    self.generate('gallerytags.html', template_values)

  def post(self, key, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if key != '':
      tag = GalleryTag.get(key)
    else:
      tag = GalleryTag()

    if self.request.get("save")!='':
      name = self.request.get("name")
      slug = self.request.get("slug")

      tag.name = name
      tag.slug = slug
      tag.put()
      memcache.flush_all()
    self.redirect("/admin/gallerytags/", True)

class AvPhotos(webapp.RequestHandler):
  def get(self, category):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    
    if category == "man":
      queryitem = File.all()
      queryitem.filter(' category = ', 'man')
      queryitem.filter(' available = ', True)
      queryitem.order('-pubDate')
      photos = queryitem.fetch(900)
      
    if category == "woman":
      queryitem = File.all()
      queryitem.filter(' category = ', 'woman')
      queryitem.filter(' available = ', True)
      photos = queryitem.fetch(900)

    if category == "funny":
      queryitem = File.all()
      queryitem.filter(' category = ', 'funny')
      queryitem.filter(' available = ', True)
      photos = queryitem.fetch(800)

    template_values = {
      'photos' : photos,
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/gallery-avphotos.html')
    self.response.out.write(template.render(path, template_values))

class AssignPhoto(webapp.RequestHandler):
  def post(self, fileId, galleryId):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)

    queryitem = File.all()
    queryitem.filter(' fileId = ', int(fileId))
    photos = queryitem.fetch(1)
    photo = photos[0]
    
    photo.available = False
    photo.galleryId = int(galleryId)
    photo.put()
    
    querygallery = Gallery.all()
    querygallery.filter(' galleryId = ', int(galleryId))
    galleries = querygallery.fetch(1)
    gallery = galleries[0]
    gallery.photosCounter += 1
    gallery.put()

    self.response.out.write("Todo ok. Photo assigned")

class MakeMainPhoto(webapp.RequestHandler):
  def post(self, fileId, galleryId):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)

    querygallery = Gallery.all()
    querygallery.filter(' galleryId = ', int(galleryId))
    galleries = querygallery.fetch(1)
    gallery = galleries[0]
    gallery.thumbnail = fileId
    gallery.put()

    self.response.out.write("Todo ok. Photo is main")

class UnassignPhoto(webapp.RequestHandler):
  def post(self, fileId, galleryId):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)

    queryitem = File.all()
    queryitem.filter(' fileId = ', int(fileId))
    photos = queryitem.fetch(1)
    photo = photos[0]

    photo.available = True
    photo.galleryId = 0
    photo.put()

    self.response.out.write("Todo ok. Photo unassigned")

class CropImage(webapp.RequestHandler):
  def get(self, category):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    photobig=self.request.get("photobig")
    
    template_values = {
      'photobig' : photobig,
      'category' : category
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/gallery-crop.html')
    self.response.out.write(template.render(path, template_values))

class SaveImage(webapp.RequestHandler):
  def post(self, item):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    photobig = self.request.get("photobig")
    posy = int(self.request.get("posy"))
    posx = int(self.request.get("posx"))

    #try:
    result = urlfetch.fetch(photobig)
    #except:
      #self.response.out.write("Image too big!")
      #return 0

    content = result.content
    img = images.Image(content)

    originalwidth = float(img.width)
    originalheight = float(img.height)
    
    ratio = float(originalwidth/originalheight)

    resizedheight = float(480)
    resizedwidth = float(320)

    calculatedwidth = math.ceil(float(float(originalwidth * resizedheight) / originalheight))
    calculatedheight = math.ceil(float(float(originalheight * resizedwidth) / originalwidth))
    
    if ratio > 0.66666667:
      resizedcontent = images.resize(content, int(calculatedwidth), int(resizedheight))
      
      left_x = float(posx / calculatedwidth)
      right_x = float((posx + 320) / calculatedwidth)

      top_y = float(posy / resizedheight)
      bottom_y = float(posy + 480 / resizedheight)

      #self.response.out.write("ratio > 4/6 - " + str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
      #return 0

    else:
      resizedcontent = images.resize(content, int(resizedwidth), int(calculatedheight))

      left_x = float(posx / resizedwidth)
      right_x = float((posx + 320) / resizedwidth)

      top_y = float(posy / calculatedheight)
      bottom_y = float((posy + 480) / calculatedheight)
      
      #self.response.out.write("ratio < 4/6 - " + str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
      #return 0

    #posx: 0, posy: 5
    #left_x: 0.0, top_y: 0.0104166666667, right_x: 1.01587301587, bottom_y: 1.01041666667

    croppedcontent = images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)
    img = images.Image(croppedcontent)

    myfile = File()
    myfile.bytes_content = db.Blob(croppedcontent)
    myfile.height = img.height
    myfile.width = img.width

    queryitem = File.all()
    queryitem.order('-fileId')
    items = queryitem.fetch(1)

    if not len(items) > 0:
      lastId = 0
    else:
      lastId = items[0].fileId

    fileId = lastId + 1
    myfile.fileId = fileId
    
    if item == "man":
      myfile.category = "man"
    if item == "woman":
      myfile.category = "woman"
    if item == "funny":
      myfile.category = "funny"
    if item == "odd":
      myfile.category = "odd"
    myfile.put()

    #self.response.out.write(str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
    self.response.out.write("/image/" + str(fileId) + "/")



class Users(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('users.html', template_values)


class UploadImage(BaseRequestHandler):
  def get(self, filekey, callback):
    imagetype = self.request.get('imagetype')
    template_values = {
      'filekey': filekey,
      'callback': callback,
      'imagetype': imagetype
    }
    self.generate('fileupload.html', template_values)

  def post(self, filekey, callback):

    for upload in self.request.POST.getall('fileupload[]'):

      #item = self.request.POST.get('fileupload')
      imagetype = self.request.get('imagetype')

      file_content = upload.file.read()
      content = db.Blob(file_content)

      myfile = File()
      img = images.Image(content)
      myfile.bytes_content = content
      myfile.height = img.height
      myfile.width = img.width
      myfile.imagetype = imagetype
      myfile.put()

      template_values = {
        'fileKey': str(myfile.key()),
        'posted': True,
        'callback': callback,
        'imagetype': imagetype
      }
    self.generate('fileupload.html', template_values)


class DeleteImage(BaseRequestHandler):
  def post(self, key):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    myfile = File.get(key)
    myfile.delete()


# Create first admin user to start working with the app.
class PopulateUsers(BaseRequestHandler):
  def get(self):
    user = CustomUser(name="Admin",
              user=users.GetCurrentUser(),
              role="admin")
    user.put()


def main():
  application = webapp.WSGIApplication([
    ('/admin/populateusers/', PopulateUsers),
    ('/admin/populateusers', PopulateUsers),
    ('/admin/upload/(.*)/(.*)/', UploadImage),
    ('/admin/image/delete/(.*)/', DeleteImage),
    ('/admin/blogs', Blogs),
    ('/admin/blogs/(.*)/(new)/', BlogAction),
    ('/admin/blogs/(.*)/(save)/', BlogAction),
    ('/admin/blogs/(.*)/(delete)/', BlogAction),
    ('/admin/blogs/(.*)/(edit)/', BlogAction),
    ('/admin/libros', Libros),
    ('/admin/libros/(.*)/(new)/', LibroAction),
    ('/admin/libros/(.*)/(save)/', LibroAction),
    ('/admin/libros/(.*)/(delete)/', LibroAction),
    ('/admin/libros/(.*)/(edit)/', LibroAction),
    ('/admin/revistas', Revistas),
    ('/admin/revistas/(.*)/(new)/', RevistaAction),
    ('/admin/revistas/(.*)/(save)/', RevistaAction),
    ('/admin/revistas/(.*)/(delete)/', RevistaAction),
    ('/admin/revistas/(.*)/(edit)/', RevistaAction),
    ('/admin/videos', Videos),
    ('/admin/videos/(.*)/(new)/', VideoAction),
    ('/admin/videos/(.*)/(save)/', VideoAction),
    ('/admin/videos/(.*)/(delete)/', VideoAction),
    ('/admin/videos/(.*)/(edit)/', VideoAction),
    ('/admin/projects', PR_Projects),
    ('/admin/projects/(.*)/(new)/', PR_ProjectAction),
    ('/admin/projects/(.*)/(save)/', PR_ProjectAction),
    ('/admin/projects/(.*)/(delete)/', PR_ProjectAction),
    ('/admin/projects/(.*)/(edit)/', PR_ProjectAction),
    ('/admin/servers', PR_Servers),
    ('/admin/servers/(.*)/(new)/', PR_ServerAction),
    ('/admin/servers/(.*)/(save)/', PR_ServerAction),
    ('/admin/servers/(.*)/(delete)/', PR_ServerAction),
    ('/admin/servers/(.*)/(edit)/', PR_ServerAction),
    ('/admin/links', PR_Links),
    ('/admin/links/(.*)/(new)/', PR_LinkAction),
    ('/admin/links/(.*)/(save)/', PR_LinkAction),
    ('/admin/links/(.*)/(delete)/', PR_LinkAction),
    ('/admin/links/(.*)/(edit)/', PR_LinkAction),
    ('/admin/', Index),
  ], debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":
  main()
